
package com.example.xiaoxueqixiangmu;

import androidx.annotation.NonNull;
import androidx.annotation.XmlRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xiaoxueqixiangmu.Fragment.MineFragment;
import com.example.xiaoxueqixiangmu.Fragment.TicketFragment;
import com.example.xiaoxueqixiangmu.Tabs.MineActivity;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.example.xiaoxueqixiangmu.utils.Md5Utils;
import com.example.xiaoxueqixiangmu.utils.NetUtils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG="LoginActiviy";
    private Button btnLogin;
    private TextView tvLostPassword;
    private EditText edtUsername;
    private EditText edtPassword;
    private CheckBox ckLogin;
    //private ProgressDialog progressDialog;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    int result=msg.arg1;
                    String sessionId=msg.obj.toString();
                    if (result==0){
                        //用户名或者密码错误，给出提示
                        edtUsername.setError("用户名或者密码错误");
                        edtUsername.requestFocus();
                    }else if(result==1){
                        //使用SPS保存
                        SharedPreferences preferences=getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor=preferences.edit();
                        //若勾选了“自动登录”，则保存正确的用户名和密码
                        if (ckLogin.isChecked()){
                            //记录用户名和加密后的密码
                            editor.putString("username",edtUsername.getText().toString());
                            editor.putString("password",Md5Utils.MD5(edtPassword.getText().toString()));
                        }
                        //TODO 如果没勾选？？？？？
                        //保存sessionId
                        editor.putString("cookie",sessionId);
                        //执行修改
                        editor.commit();

                        //页面跳转到MainActivity
                        Intent intent=new Intent(LoginActivity.this, MyFragmentActivity.class);
                        startActivity(intent);
                        //将登录从堆栈清除
                        LoginActivity.this.finish();
                    }
                    break;
                case 2:
                    Toast.makeText(LoginActivity.this,"服务器错误，请重试！",Toast.LENGTH_LONG).show();;
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvLostPassword=(TextView)findViewById(R.id.textForget);
        edtUsername=(EditText)findViewById(R.id.edtName);
        edtPassword=(EditText)findViewById(R.id.edtPwd);
        ckLogin=(CheckBox) findViewById(R.id.checkBox);
        //获取组件对象
        btnLogin=(Button)findViewById(R.id.btnLogin);
        //绑定监听器
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edtUsername.getText().toString())){
                    edtUsername.requestFocus();
                    edtUsername.setError("请输入用户名");
                }else if (TextUtils.isEmpty(edtPassword.getText().toString())){
                    edtPassword.requestFocus();
                    edtPassword.setError("请输入密码");
                }else {
                    //1.检测网络状态
                    if (!NetUtils.check(LoginActivity.this)){
                        Toast.makeText(LoginActivity.this,"网络异常！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //弹出对话框
                    //progressDialog=ProgressDialog.show(LoginActiviy.this,null,"正在加载中...",false,true);
                    //2.网络正常时发起网络连接，传递用户名和密码
                    //多线程
                    new Thread(){
                        @Override
                        public void run() {
                            Message msg=Message.obtain();
                            String result="";
                            try {
                                //使用OKHttpClient连接网络
                                OkHttpClient client=new OkHttpClient();
                                RequestBody requestBody=new FormBody.Builder()
                                        .add("username",edtUsername.getText().toString())
                                        .add("password",Md5Utils.MD5(edtPassword.getText().toString()))
                                        .build();
                                Request request=new Request.Builder()
                                        .url(Constant.Host+"/Login")
                                        .post(requestBody)
                                        .build();
                                Response response=client.newCall(request).execute();
                                String responseData=response.body().string();
                                Log.d(TAG,"获取的服务器数据:"+responseData);
                                //解析成功接收到的数据
                                if (response.isSuccessful()){
                                    //进行PULL解析
                                    //1.生成解析器
                                    XmlPullParser parser= Xml.newPullParser();
                                    //2.引入要解析的流
                                    //parser.setInput(response.body().byteStream(),"UTF-8");
                                    parser.setInput(new StringReader(responseData));
                                    //3.事件类型解析
                                    int type=parser.getEventType();
                                    while(type!=XmlPullParser.END_DOCUMENT){
                                        switch (type){
                                            case XmlPullParser.START_TAG:
                                                if ("result".equals(parser.getName())){
                                                    result=parser.nextText();
                                                    Log.d(TAG,"解析出的服务器响应信息result="+result);
                                                }
                                                break;
                                        }
                                        type=parser.next();
                                    }
                                    //读取sessionId
                                    Headers headers=response.headers();
                                    Log.d(TAG,"headers:"+headers);
                                    List<String> cookies=headers.values("Set-Cookie");
                                    Log.d(TAG,"Set-Cookie:"+cookies);
                                    String session=cookies.get(0);
                                    Log.d(TAG,"onResponse-size:"+session);
                                    String sessionId=session.substring(0,session.indexOf(";"));
                                    Log.d(TAG,"session is:"+sessionId);
                                    //发送消息
                                    msg.what=1;
                                    msg.arg1=Integer.parseInt(result);
                                    msg.obj=sessionId;
                                }else {
                                    //网络状态异常
                                    msg.what=2;
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                msg.what=2;
                            } catch (XmlPullParserException e) {
                                e.printStackTrace();
                                msg.what=2;
                            }
                            handler.sendMessage(msg);
                        }
                    }.start();
                }
            }
        });
    }





}
   /* private static final String TAG="LoginActiviy";
    private EditText edtName,edtPwd;
    private TextView textForget;
    private Button btnLogin;
    private CheckBox checkBox;
    private SharedPreferences sp;
    private  ProgressDialog progressDialog;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //消失的进度对话框
           *//* if (progressDialog!=null){
                progressDialog.dismiss();
            }*//*
            switch (msg.what){
                case 1:
                    //取出JSESSIONID
                    String jsessionid=(String)msg.obj;
                    int result=msg.arg1;
                   *//* if (0==result){
                        //0是用户名以及密码错误

                    }else  if (1==result){
                        //1说明密码以及用户名正确
                        if (checkBox.isChecked()){

                        }

                    }*//*
                    break;
                case 2:

                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edtName=findViewById(R.id.edtName);
        edtPwd=findViewById(R.id.edtPwd);
        checkBox=findViewById(R.id.checkBox);
        textForget=findViewById(R.id.textForget);
        btnLogin=findViewById(R.id.btnLogin);

//sharedpreference保存密码
        sp=getSharedPreferences("info",MODE_PRIVATE);
        String username = sp.getString("username", "");
        String password = sp.getString("password", "");
        edtName.setText(username);
        edtPwd.setText(password);


//登录按钮的点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
               *//* String Name=edtName.getText().toString().trim();
                String Pwd=edtPwd.getText().toString().trim();*//*

                //密码判断
               *//* if (Name.equals("dong")&&Pwd.equals("dong")){
                    Intent intent=new Intent(LoginActivity.this, MyFragmentActivity.class);
                    startActivity(intent);
                }else
                    if (Name.isEmpty()||Pwd.isEmpty()){
                        Toast.makeText(LoginActivity.this,"账户以及密码不能为空",Toast.LENGTH_SHORT).show();
                    }else if (Name!="阔乐"||Pwd!="282453"){
                        Toast.makeText(LoginActivity.this,"密码或账户名错误",Toast.LENGTH_SHORT).show();

                    }*//*
                if (TextUtils.isEmpty(edtName.getText().toString())) {
                    edtName.setError("请输入用户名");
                    edtName.requestFocus();
                    Toast.makeText(LoginActivity.this,"账户以及密码不能为空",Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(edtPwd.getText().toString())) {
                    edtPwd.setError("请输入密码");
                    edtPwd.requestFocus();
                } else {
                    if (!NetUtils.check(LoginActivity.this)) {
                        Toast.makeText(LoginActivity.this, "服务器拦连接不成", Toast.LENGTH_SHORT).show();
                        return;
                    }


                    //弹出一个对话框
                    progressDialog = ProgressDialog.show(LoginActivity.this, null, "服务器正在加载中", true, false);
                    //线程处理与服务器交互
                new Thread(){
                    @Override
                    public void run() {
                        Message msg=handler.obtainMessage();
                        String result="";
                        try {
                            //使用OKHttpClient连接网络
                            OkHttpClient  client=new OkHttpClient();
                            RequestBody requestBody= new FormBody.Builder()
                                    .add("username",edtName.getText().toString())
                                    .add("password",Md5Utils.MD5(edtPwd.getText().toString()))
                                    .build();
                            Request request=new Request.Builder()
                                    .url(Constant.Host+"/Login")
                                    .post(requestBody)
                                    .build();
                            Response response=client.newCall(request).execute();
                            String responseData=response.body().string();
                           Log.d(TAG,"获取服务器的数据："+responseData);
                            //解析成功接收到的数据
                            if (response.isSuccessful()){
                                //进行PULL解析
                                //1.生成解析器
                                XmlPullParser parser= Xml.newPullParser();
                                //2.引入要解析的流
                                //parser.setInput(response.body()).byteStream(),"UTF-8");
                                parser.setInput(new StringReader(responseData));
                                //3.事件类型解析
                                int type=parser.getEventType();
                                while (type!=XmlPullParser.END_DOCUMENT){

                                }
                            }

                        } catch (IOException | XmlPullParserException e) {
                            e.printStackTrace();
                        }
                    }



                }.start();}
                    *//*new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            Message msg = handler.obtainMessage();
                            try {
                                URL url = new URL(Constant.Host + "/Login");
                                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                                //设置连接超时，读取超时
                                httpURLConnection.setConnectTimeout(Constant.REQUEST_TIMEOUT);
                                httpURLConnection.setReadTimeout(Constant.SO_TIMEOUT);
                                //发送POST请求
                                httpURLConnection.setDoOutput(true);
                                httpURLConnection.setDoInput(true);
                                //设置不使用缓存
                                httpURLConnection.setUseCaches(false);
                                //设置请求属性
                                httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                                httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                                httpURLConnection.setRequestProperty("Charset", "UTF-8");

                                //获取输出流
                                PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
                                //请求参数
                                String params = "username=" + edtName.getText().toString() + "&password=" + Md5Utils.MD5(edtPwd.getText().toString());
                                System.out.println("发往服务器的内容" + params);
                                printWriter.write(params);
                                printWriter.flush();
                                printWriter.close();

                                //处理获取服务器给的响应状态
                                int resultCode = httpURLConnection.getResponseCode();
                                if (resultCode == HttpURLConnection.HTTP_OK) {
                                    //打印结果
                                    InputStream inputStream = httpURLConnection.getInputStream();
                                    StringBuffer sb = new StringBuffer();
                                    String readLine = new String();
                                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                                    while ((readLine = reader.readLine()) != null) {
                                        sb.append(readLine).append("\n");
                                    }
                                    System.out.println("服务器返回的结果" + sb.toString());

                                    //XML解析数据
                                    XmlPullParser parser = Xml.newPullParser();
                                    //设置内容
                                    parser.setInput(new StringReader(sb.toString()));
                                    int type = parser.getEventType();
                                    String result = null;
                                    while (type != XmlPullParser.END_DOCUMENT) {
                                        switch (type) {

                                            //起始标签
                                            case XmlPullParser.START_TAG:
                                                if ("result".equals(parser.getName())) {
                                                    result = parser.nextText();
                                                    //打印result的数据
                                                    Log.d("result:", result);
                                                }
                                                break;

                                        }
                                        type = parser.next();
                                    }
                                    //记录session的ID
                                    String value = "";
                                    String responseCookie = httpURLConnection.getHeaderField("Set-Cookie");
                                    Log.d("responseCookie::", responseCookie);

                                    //判断cookie的值，不为空就取出session的数值
                                    if (responseCookie != null) {
                                        String sessionString = responseCookie.substring(0, responseCookie.indexOf(";"));
                                        value = sessionString.split("=")[1];

                                    }
                                    Log.d("value::", "JSESSIONID:" + value);
                                    inputStream.close();
                                    msg.what = 1;
                                    msg.arg1 = Integer.parseInt(result);
                                    msg.obj = "JESSION=" + value;
                                } else {
                                    msg.what = 2;

                                }


                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                                msg.what = 2;
                            } catch (IOException e) {
                                e.printStackTrace();
                                msg.what = 2;
                            } catch (XmlPullParserException e) {
                                e.printStackTrace();
                                msg.what = 2;
                            }
                            handler.sendMessage(msg);
                        }
                    }.start();*//*

               *//* if (checkBox.isChecked()){
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("username",Name);
                    editor.putString("password", Pwd);
                    editor.commit(); //一定要提交


                }*//*

                }

        });
        textForget.setText(Html.fromHtml("<a href=\"http://106.55.50.79:8080/My12306"));
        textForget.setMovementMethod(LinkMovementMethod.getInstance());

    }
}*/